package com.activities;


import java.util.Arrays;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.Animations.AnimUtil;
import com.Data.Post;
import com.Data.Post.OnGetPicturesCompleted;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Init.ImageDownloaderInit;
import com.Managers.PictureManagerClass;
import com.SoapClasses.SoapUtil;
import com.TextFormat.UtilFonts;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.shareup.R;


/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

public class ImagePagerActivity extends FragmentActivity {

    private static final String STATE_POSITION = "STATE_POSITION";

    static int[] imageIds;

    static String[] imageUrls;

    static int pagerPosition;

    private Post actualPicture;

    private ImageView profileImage;

    private TextView profileName;

    private ProgressBar progress;

    private boolean sMenuOpened;

    private RelativeLayout containerInfo;

    ImagePagerAdapter adapter;

    ImageLoader imageLoader;

    DisplayImageOptions options;

    ViewPager pager;

    SlidingMenu sMenu;

    private class ImagePagerAdapter extends PagerAdapter implements OnPageChangeListener {

        private int[] images;

        public void setImages(int[] images) {

            this.images = images;
        }

        private LayoutInflater inflater;

        ImagePagerAdapter(int[] images) {

            this.images = images;
            inflater = getLayoutInflater();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            container.removeView((View) object);
        }

        @Override
        public int getCount() {

            return images.length;
        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {

            View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
            assert imageLayout != null;
            final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

            downloadUserInfo(imageIds[position], new OnGetPicturesCompleted() {

                @Override
                public void Completed(Post[] result) {

                    actualPicture = result[0];

                    setUserInfo();

                    PictureManagerClass.scalePostImage(actualPicture.getWidth(), actualPicture.getHeight(), imageView);

                    imageLoader.displayImage(actualPicture.getPathFull(), imageView, options, new SimpleImageLoadingListener() {

                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                            spinner.setVisibility(View.GONE);

                        }

                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                            String message = null;
                            switch (failReason.getType()) {
                                case IO_ERROR:
                                    message = "Input/Output error";
                                    break;
                                case DECODING_ERROR:
                                    message = "Image can't be decoded";
                                    break;
                                case NETWORK_DENIED:
                                    message = "Downloads are denied";
                                    break;
                                case OUT_OF_MEMORY:
                                    message = "Out Of Memory error";
                                    break;
                                case UNKNOWN:
                                    message = "Unknown error";
                                    break;
                            }
                            Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();

                            spinner.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadingStarted(String imageUri, View view) {

                            spinner.setVisibility(View.VISIBLE);

                        }
                    });
                }
            });

            view.addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {

            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {

        }

        @Override
        public Parcelable saveState() {

            return null;
        }

        /*
         * (non-Javadoc)
         * @see android.support.v4.view.ViewPager.OnPageChangeListener#
         * onPageScrollStateChanged(int)
         */
        @Override
        public void onPageScrollStateChanged(int arg0) {

            // TODO Auto-generated method stub

        }

        /*
         * (non-Javadoc)
         * @see
         * android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled
         * (int, float, int)
         */
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

            // TODO Auto-generated method stub

        }

        /*
         * (non-Javadoc)
         * @see
         * android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected
         * (int)
         */
        @Override
        public void onPageSelected(int position) {

            if (position == getCount() - 1)
                downloadMore(position);

        }
    }

    private void downloadMore(final int position) {

        Post pst = new Post(SoapUtil.MENU_VIEW, imageIds.length);
        pst.setCallbackGetPictures(new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                Log.e("desc", "completada");
                int[] back = Arrays.copyOf(imageIds, imageIds.length);
                imageIds = new int[back.length + result.length];
                for (int i = 0; i < back.length; i++) {
                    imageIds[i] = back[i];
                }
                for (int i = imageIds.length; i < result.length
                            + back.length; i++) {
                    imageIds[i] = result[i].getID();
                }

                addToAdapter(imageIds, position);
            }
        });
        pst.execute();
    }

    private void setLoading() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_image_pager);

        Bundle bundle = getIntent().getExtras();
        assert bundle != null;

        pagerPosition = bundle.getInt("POSITION", 0);
        imageIds = bundle.getIntArray("IDS");

        if (savedInstanceState != null)
            pagerPosition = savedInstanceState.getInt(STATE_POSITION);

        addToAdapter(imageIds, pagerPosition);

        options = ImageDownloaderInit.getOptionsForList();
        setConf();

        Init();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (sMenuOpened) {
                sMenu.toggle();
                sMenuOpened = false;
            }
            else
                exit();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putInt(STATE_POSITION, pager.getCurrentItem());
    }

    private void addToAdapter(int[] imageIds, int imageIds2) {

        if (adapter == null) {
            adapter = new ImagePagerAdapter(imageIds);
            pager = (ViewPager) findViewById(R.id.pager);
            pager.setAdapter(adapter);
            pager.setOnPageChangeListener(adapter);
            pager.setCurrentItem(imageIds2);
        }
        else {
            adapter = new ImagePagerAdapter(imageIds);
            pager.setAdapter(adapter);
            pager.setOnPageChangeListener(adapter);
            pager.setCurrentItem(imageIds2);

            adapter.notifyDataSetChanged();
        }

    }

    private void exit() {

        finish();
        AnimUtil.getActivityTransition(this, false);
    }

    private void downloadUserInfo(int IDPicture, OnGetPicturesCompleted callback) {

        Log.e("DESCARGANDO", "USER INFO");

        Post pst = new Post(SoapUtil.MODE_GET_PUBLICATION_INFO);
        pst.setID(IDPicture);
        pst.setCallbackGetPictures(callback);
        pst.execute();
    }

    private void Init() {

        ImageView infoB = (ImageView) findViewById(R.id.button_info);
        infoB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                sMenu.toggle();

            }
        });
        profileImage = (ImageView) findViewById(R.id.user_image_profile);
        profileName = (TextView) findViewById(R.id.user_name);
        UtilFonts.setTextBoldFont(profileName);
        progress = (ProgressBar) findViewById(R.id.loading_progress);
        containerInfo = (RelativeLayout) findViewById(R.id.layout_container);
    }

    private void setConf() {

        ImageDownloaderInit.config(this, "");
        imageLoader = ImageLoader.getInstance();
    }

    private void setUserInfo() {

        Log.e("SETEANDO", "USER INFO");
        profileName.setText(actualPicture.getUser().getRealName());

        ProfilePictureDownloader pd = new ProfilePictureDownloader();
        pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

            @Override
            public void completed(Bitmap result) {

                progress.setVisibility(View.GONE);
                AnimUtil.animatePictureChanges(profileImage, result);

            }
        });
        pd.execute(actualPicture.getUser().getProfilePicture());

    }

    @Override
    protected void onResume() {

        super.onResume();
    }
}
